package com.example.interceptor;

import com.example.constant.Constants;
import com.example.model.Result;
import com.example.model.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created with IntelliJ IDEA.
 * Description: 1.创建拦截器类
 * User: bjc
 * Date: 2025-07-26
 * Time: 10:44
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("LoginInterceptor preHandle");
        //配置用户登录校验
        //1.获取session，并判断session中存储的信息是否存在
        HttpSession session = request.getSession();
        UserInfo loginUserInfo = (UserInfo) session.getAttribute(Constants.USER_SESSION_KEY);
        //2.判断用户信息是否存在
        if(loginUserInfo == null || loginUserInfo.getId() <0){
            response.setStatus(401);//表示用户未登录
            log.info("进行拦截");

            return false;//拦截
        }
        log.info("用户已登录，放行");
        return true;
    }
}
